package cn.lili.controller.member;

import cn.lili.common.enums.ResultCode;
import cn.lili.common.enums.ResultUtil;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.security.AuthUser;
import cn.lili.common.security.OperationalJudgment;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.utils.CurrencyUtil;
import cn.lili.common.vo.PageVO;
import cn.lili.common.vo.ResultMessage;
import cn.lili.modules.member.entity.dos.Member;
import cn.lili.modules.member.entity.vo.MemberVO;
import cn.lili.modules.member.service.MemberService;
import cn.lili.modules.order.order.entity.vo.OrderDetailVO;
import cn.lili.modules.payment.kit.CashierSupport;
import cn.lili.modules.payment.kit.dto.PayParam;
import cn.lili.modules.payment.kit.params.dto.CashierParam;
import cn.lili.modules.transfer.entity.Transfer;
import cn.lili.modules.transfer.entity.vo.TransferVO;
import cn.lili.modules.transfer.service.TransferService;
import cn.lili.modules.wallet.entity.enums.WalletOwnerEnum;
import cn.lili.mybatis.util.PageUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * create by yudan on 2022/6/30
 */
@RestController
@Api(tags = "买家端,会员转账接口")
@RequestMapping("/buyer/member/transfer")
public class TransferBuyerController {

	@Autowired
	private MemberService memberService;

	@Autowired
	private CashierSupport cashierSupport;

	@Autowired
	private TransferService transferService;

	@ApiOperation(value = "查询转账列表")
	@GetMapping
	public ResultMessage<IPage<TransferVO>> queryMineOrder(PageVO pageVO, String owner, String type) {
		AuthUser authUser = Objects.requireNonNull(UserContext.getCurrentUser());
		if (authUser == null) {
			throw new ServiceException(ResultCode.USER_AUTHORITY_ERROR);
		}
		QueryWrapper<TransferVO> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("payment_wallet", owner);
		queryWrapper.eq("state", "success");
		if ("in".equals(type)) {
			// 收款记录
			queryWrapper.eq("payee", authUser.getId());
		} else if ("out".equals(type)) {
			// 付款人
			queryWrapper.eq("payer", authUser.getId());
		} else {
			queryWrapper.and(qw -> qw.eq("payee", authUser.getId()).or().eq("payer", authUser.getId()));
		}
		queryWrapper.eq("state", "success");
		queryWrapper.eq("payer", authUser.getId());
		queryWrapper.orderByDesc("payment_time");
		IPage<TransferVO> transferIPage = transferService.queryByParams(PageUtil.initPage(pageVO), queryWrapper);
		if (transferIPage != null && transferIPage.getRecords().size() > 0) {
			for (TransferVO transfer : transferIPage.getRecords()) {
				Double commission = 0D;
				if (transfer.getCommission() != null) {
					commission = transfer.getCommission();
				}
				if (authUser.getId().equals(transfer.getPayee()) && owner.equals(WalletOwnerEnum.RECHARGE.name())) {
					transfer.setType("转入");
					transfer.setTransferMoneyStr(
							"+" + CurrencyUtil.add(transfer.getTransferMoney(), commission).toString());
				} else if (authUser.getId().equals(transfer.getPayer())) {
					transfer.setType("转出");
					transfer.setTransferMoneyStr(
							"-" + CurrencyUtil.add(transfer.getTransferMoney(), commission).toString());
				}
			}
		}
		return ResultUtil.data(transferIPage);
	}

	@ApiOperation(value = "转账明细")
	@ApiImplicitParams({@ApiImplicitParam(name = "sn", value = "转账明细", required = true, paramType = "path")})
	@RequestMapping(value = "/detail/{sn}")
	public ResultMessage<Transfer> detail(@NotNull(message = "转账编号不能为空") @PathVariable("sn") String sn) {
		return ResultUtil.data(transferService.getTransferByTradeSn(sn));
	}

	@ApiOperation(value = "转账总额")
	@RequestMapping("/allTransfer")
	public ResultMessage<Map<String, Object>> allTransfer(String owner) {
		AuthUser authUser = Objects.requireNonNull(UserContext.getCurrentUser());
		if (authUser == null) {
			throw new ServiceException(ResultCode.USER_AUTHORITY_ERROR);
		}
		Map<String, Object> map = new HashMap<>();
		Double inMoney = 0D;
		Double outMoney = 0D;
		QueryWrapper<TransferVO> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("payment_wallet", owner);
		queryWrapper.eq("state", "success");
		queryWrapper.eq("payer", authUser.getId());
		List<TransferVO> transferIPage = transferService.queryByParamsList(queryWrapper);
		if (transferIPage != null && transferIPage.size() > 0) {
			for (TransferVO transfer : transferIPage) {
				if (authUser.getId().equals(transfer.getPayee()) && owner.equals(WalletOwnerEnum.RECHARGE.name())) {
					// 转入
					inMoney = CurrencyUtil.add(inMoney, transfer.getTransferMoney());
				} else if (authUser.getId().equals(transfer.getPayer())) {
					// //转出
					outMoney = CurrencyUtil.add(outMoney, transfer.getTransferMoney(), transfer.getCommission());
				}
			}
		}
		map.put("inMoney", inMoney);
		map.put("outMoney", outMoney);
		return ResultUtil.data(map);
	}

	@ApiOperation(value = "根据手机号查询会员信息")
	@ApiImplicitParam(name = "mobile", value = "手机号", dataType = "String", paramType = "path")
	@RequestMapping("/{mobile}")
	public ResultMessage<MemberVO> getUserInfo(@PathVariable String mobile) {
		QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("m.mobile", mobile);
		queryWrapper.orderByAsc("c.LEVEL");
		queryWrapper.last("limit 1");
		MemberVO memberVO = memberService.findByPhone(queryWrapper);
		return ResultUtil.data(memberVO);
	}

	@RequestMapping(value = "/tradeNativeDetail")
	@ApiOperation(value = "获取支付详情(转账)")
	public ResultMessage paymentNative(@Validated PayParam payParam) {
		CashierParam cashierParam = cashierSupport.cashierParamsNative(payParam);
		return ResultUtil.data(cashierParam);
	}

}
